package l1j.opqlo.NewSystem.地圖限時;

import java.util.Collection;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.Thread.PcOtherThreadPool;
import l1j.server.server.model.L1Teleport;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_SystemMessage;
import static l1j.server.server.model.skill.L1SkillId.MapTimer;

public class MapTimer extends TimerTask {

	private ScheduledFuture<?> _timer;

	private static final Logger _log = Logger.getLogger(MapTimer.class.getName());

	@Override
	public void run() {
		try {
			final MapTimeTable table = MapTimeTable.getInstance();

			final Collection<L1PcInstance> list = L1World.getInstance().getAllPlayers();

			if (list.isEmpty()) {
				return;
			}
			for (final L1PcInstance pc : list) {
				if (pc.isGm()) {
					continue;
				}

				if (pc.isDead() || pc.isTeleport()) { // 角色死亡時略過此次計時
					continue;
				}

				if (pc.hasSkillEffect(MapTimer)) { // 持有狀態 略過此次計時
					continue;
				}

				if (!table.isInMap(pc.getMapId())) { // 已經離開限定地圖
					// if(!pc.hasSkillEffect(AI_TimeEffect)&&!pc.hasSkillEffect(AI_CheckEffect)){
					// pc.killSkillEffectTimer(MapTimer);
					continue;
				}

				L1Teleport.teleport(pc, 33084, 33393, (short) 4, 4, true);
				pc.sendPackets(new S_SystemMessage("時間到囉，歡迎下次再來!!"));
				// list.remove(pc);
			}
		} catch (final Exception e) {
			_log.log(Level.WARNING, "地圖計時狀態異常，重新啟動");
			PcOtherThreadPool.get().cancel(this._timer, false);
			final MapTimer restart = new MapTimer();
			restart.start();
		}
	}

	public void start() {
		final int timeMillis = 5000;
		this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(this,timeMillis, timeMillis);
	}

}
